package com.chaoyi.dao.mongodb;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.chaoyi.config.MongoConfig;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;

public enum MongoClientSingle {
	INSTANCE;
	
	private final MongoClient mongoClient;
	
	MongoClientSingle(){
		X509TrustManager tm = new X509TrustManager(){
			@Override
			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			}
			@Override
			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			}
			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}};
		SSLContext sslContext;
		try {
			sslContext = SSLContext.getInstance("SSL");
			sslContext.init(null, new TrustManager[]{tm}, null);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} 
		MongoClientOptions.Builder builder = MongoClientOptions.builder()
													.sslEnabled(true)
													.socketFactory(sslContext.getSocketFactory())
													.sslInvalidHostNameAllowed(true)
													.minConnectionsPerHost(1)
													.connectionsPerHost(3)
													.threadsAllowedToBlockForConnectionMultiplier(3)
													.serverSelectionTimeout(0)
													.maxWaitTime(3000)
													.maxConnectionIdleTime(30000)
													.maxConnectionLifeTime(60000)
													.connectTimeout(2000)
													.socketTimeout(3000)
													.socketKeepAlive(true);
		MongoClientURI connectionString = new MongoClientURI("mongodb://"+MongoConfig.mongoUser+":"+MongoConfig.mongoPwd
														+"@"+MongoConfig.mongoIp+":"+MongoConfig.mongoPort,builder);
		mongoClient = new MongoClient(connectionString);
	}
	
	public MongoClient getClient(){
		return mongoClient;
	}
	
}
